package spring.cloud.tasks.executor.name_space;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.utils.SystemEnvProperties;

@Slf4j
@Setter
@Getter
public class NameSpaceConfiguration {
    /**
     * 最大重试次数.
     */
    public static final int MIN_RETRY_TIMES = 3;
    /**
     * 连接Zookeeper服务器的列表. 包括IP地址和端口号,多个地址用逗号分隔。如:host1:2181,host2:2181
     */
    private String connectString;
    /**
     * 命名空间.
     */
    private String nameSpace;
    /**
     * 连接超时时间. 单位毫秒.
     */
    private int connectionTimeoutMs;
    /**
     * 会话超时时间. 单位毫秒.
     */
    private int sessionTimeoutMs;
    /**
     * 等待重试的间隔时间的初始值. 单位毫秒.
     */
    private int baseSleepTimeMs;
    private int maxRetries;
    /**
     * 等待重试的间隔时间的最大值. 单位毫秒.
     */
    private int maxSleepMs;
    /**
     * 连接Zookeeper的权限令牌. 缺省为不需要权限验证.
     */
    private String digest;

    /**
     * 包含了必需属性的构造器.
     *
     * @param connectString   连接Zookeeper服务器的列表
     * @param nameSpace       命名空间
     * @param baseSleepTimeMs 等待重试的间隔时间的初始值
     * @param maxRetries      最大重试次数
     * @param maxSleepMs      等待重试的间隔时间的最大值
     */
    public NameSpaceConfiguration(final String connectString, final String nameSpace, final int baseSleepTimeMs, final int maxRetries, final int maxSleepMs) {
        this.connectString = connectString;
        this.nameSpace = nameSpace;
        this.baseSleepTimeMs = baseSleepTimeMs;
        this.maxRetries = maxRetries;
        this.maxSleepMs = maxSleepMs;
    }

    public NameSpaceConfiguration(final String connectString, final String nameSpace, final int baseSleepTimeMs, final int maxSleepMs) {
        this.connectString = connectString;
        this.nameSpace = nameSpace;
        this.baseSleepTimeMs = baseSleepTimeMs;
        this.maxSleepMs = maxSleepMs;
        this.maxRetries = maxRetries();
    }

    private int maxRetries() {
        int maxRetries = SystemEnvProperties.ZK_CLIENT_RETRY_TIMES;
        return maxRetries > NameSpaceConfiguration.MIN_RETRY_TIMES ? maxRetries : NameSpaceConfiguration.MIN_RETRY_TIMES;
    }
}
